import { FC, MouseEvent } from "react";
import classNames from "classnames";

import { getComponentConfByType } from "../../../../../components/QuestionComponents";

import {
  changeSelectedId,
  ComponentInfoType,
  moveComponent,
} from "../../../../../store/componentsReducer";
import useGetComponentInfo from "../../../../../hooks/useGetComponentInfo";
import { useDispatch } from "react-redux";
import useBindCanvaskeyPress from "../../../../../hooks/useBindCanvaskeyPress";
import SortableContainer from "../../../../../components/DragSortable/SortableContainer";
import SortableItem from "../../../../../components/DragSortable/SortableItem";
const EditCanvas: FC = () => {
  const { componentList, selectedId } = useGetComponentInfo();
  const dispatch = useDispatch();

  // 绑定快捷键
  useBindCanvaskeyPress();

  function genComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo; // 每个组件的信息，是从 redux store 获取的（服务端获取）

    const componentConf = getComponentConfByType(type);
    if (componentConf == null) return null;

    const { Component } = componentConf;
    return <Component {...props} />;
  }
  // 点击组件，选中
  function handleClick(event: MouseEvent, id: string) {
    event.stopPropagation(); // 阻止冒泡
    dispatch(changeSelectedId(id));
  }
  // SortableContainer 组件的 items 属性，需要每个 item 都有 id
  const componentListWithId = componentList.map((i) => {
    return { ...i, id: i.fe_id };
  });

  // 拖拽排序结束
  const handleDragEnd = (oldIndex: number, newIndex: number) => {
    dispatch(moveComponent({ oldIndex, newIndex }));
  };
  return (
    <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
      <div className="min-h-100% bg-#fff overflow-hidden">
        {componentList
          .filter((i) => !i.isHidden)
          .map((i) => {
            const { fe_id, isLocked } = i;
            const wrapperDefaultClassName =
              "m-3 b-1 b-solid b-#fff p-3 b-rd-[3px] hover-b-#d9d9d9";
            const selectedClassName = "important-b-#1890ff ";
            const lockedClassName = "opacity-50 cursor-not-allowed";
            const wrapperClassName = classNames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: fe_id === selectedId,
              [lockedClassName]: isLocked,
            });
            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div
                  className={wrapperClassName}
                  onClick={(e: MouseEvent) => {
                    handleClick(e, fe_id);
                  }}
                >
                  <div className="pointer-events-none">
                    {genComponent(i as ComponentInfoType)}
                  </div>
                </div>
              </SortableItem>
            );
          })}
      </div>
    </SortableContainer>
  );
};
export default EditCanvas;
